const child_process = require("child_process");
const process = require("process");
const util = require("util");
const {getConfig} = require('./index')
const logger = require('./logger')(getConfig().isLog)
function execCmd(cmd, options = { verbose: false }) {
  let [shell, ...args] = cmd.split(" ").filter(Boolean);
  const { verbose, ...others } = options;
  return new Promise((resolve, reject) => {
    if (shell === "npm") {
      shell = process.platform === "win32" ? "npm.cmd" : "npm";
    }
    let child = child_process.spawn(shell, args, others);
    let stdout = "";
    let stderr = "";
    child.stdout &&
      child.stdout.on("data", (buf) => {
        stdout = `${stdout}${buf}`;
        if (verbose) {
          logger.info(`${buf}`);
        }
      });
    child.stderr &&
      child.stderr.on("data", (buf) => {
        stderr = `${stderr}${buf}`;
        if (verbose) {
          logger.error(buf);
        }
      });
    child.on("exit", (code) => {
      if (code !== 0) {
        const reason = stderr || "some unknown error";
        reject(`exited with code ${code} due to ${reason}`);
      } else {
        resolve({ stdout, stderr });
      }
      child.kill();
      child = null;
    });
    child.on("error", (err) => {
      reject(err.message);
      child.kill();
      child = null;
    });
  });
}
const exec = util.promisify(child_process.exec);
const cd = (dir) => {
  try {
    const curDir = process.cwd();
    process.chdir(dir);
    process.env.OLDPWD = curDir;
  } catch (err) {
    logger.error(err);
  }
};
module.exports = {
  execCmd,
  exec,
  cd,
};
